package com.yycx.module.bbs.provider.handler;

import com.yycx.common.base.entity.EntityMap;
import com.yycx.common.base.utils.FlymeUtils;
import com.yycx.common.mybatis.interceptor.PageInterceptor;
import com.yycx.common.mybatis.model.PageParams;
import com.yycx.common.mybatis.query.CriteriaQuery;
import com.yycx.common.utils.DateUtils;
import com.yycx.module.bbs.client.entity.BbsComment;
import com.yycx.module.bbs.client.entity.BbsContent;
import com.yycx.module.bbs.provider.service.BbsCommentService;
import com.yycx.module.bbs.provider.service.BbsContentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

/**
 * 用户帖子评论跟回复列表
 *
 * @author zyf
 */
@Component("userBbsCommentListHandler")
public class UserBbsCommentListHandler implements PageInterceptor<BbsComment> {

    @Autowired
    private BbsContentService bbsContentService;

    @Autowired
    private BbsCommentService bbsCommentService;


    @Override
    public void prepare(CriteriaQuery<BbsComment> cq, PageParams pageParams, EntityMap params) {
        cq.select(BbsContent.class,"contentType");
        cq.createJoin(BbsContent.class);
        cq.orderByDesc("comment.createTime");
    }

    @Override
    public void complete(CriteriaQuery<BbsComment> cq, List<EntityMap> result, EntityMap extra) {
        result.forEach(entityMap -> {
            Long contentId = entityMap.getLong("contentId");
            Long replyCommentId = entityMap.getLong("replyCommentId");
            if (FlymeUtils.isNotEmpty(replyCommentId)) {
                BbsComment bbsComment = bbsCommentService.getById(replyCommentId);
                if (FlymeUtils.isNotEmpty(bbsComment)) {
                    entityMap.put("showContent", bbsComment.getReplyContent());
                    entityMap.put("replyTag", BbsComment.class.getSimpleName());
                }
            } else {
                if (FlymeUtils.isNotEmpty(contentId)) {
                    BbsContent bbsContent = bbsContentService.getById(contentId);
                    if (FlymeUtils.isNotEmpty(bbsContent)) {
                        entityMap.put("showContent", bbsContent.getTitle());
                        entityMap.put("coverImage", bbsContent.getCoverImage());
                    }
                    entityMap.put("replyTag", BbsContent.class.getSimpleName());
                }
            }
            Date createTime = entityMap.get("createTime");
            String showTime = DateUtils.formatFromTodayCn(createTime);
            entityMap.put("showTime", showTime);
        });
    }
}
